package mia.beans;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import org.apache.commons.io.FilenameUtils;
import org.apache.myfaces.custom.fileupload.UploadedFile;
import org.hibernate.Session;

import com.ibm.icu.text.DateFormat;
import com.ibm.icu.text.SimpleDateFormat;
import com.ibm.icu.util.Calendar;

import mia.dao.AdvertisementEntityDAO;
import mia.dao.AdvertisementTypeEntityDAO;
import mia.dao.CategoryEntityDAO;
import mia.dao.UserEntityDAO;
import mia.entity.AdvertisementEntity;
import mia.entity.AdvertisementTypeEntity;
import mia.entity.AttachmentEntity;
import mia.entity.CategoryEntity;
import mia.entity.UserEntity;
import mia.util.HibernateManager;

@ManagedBean(name = "advertisementRegBean")
@RequestScoped
public class AdvertisementRegBean {

	@ManagedProperty("#{userLoginBean.user}")
	private UserEntity user;

	private AdvertisementEntity advertisement = new AdvertisementEntity();

	private Map<String, AdvertisementTypeEntity> types = null;
	private String selectedType;

	private Map<String, CategoryEntity> categories = null;
	private String selectedCategory;

	private String attachment1 = "";
	private String attachment2 = "";
	private String attachment3 = "";

	private String regAdvertisementStatus;
	private int iterator = 1;

	private int newId;
	private UploadedFile upFile;
	private boolean avalible = true;

	public UploadedFile getUpFile() {
		return upFile;
	}

	public void setUpFile(UploadedFile upFile) {
		this.upFile = upFile;
	}

	public boolean isAvalible() {
		return avalible;
	}

	public void setAvalible(boolean avalible) {
		this.avalible = avalible;
	}

	public int getNewId() {
		return newId;
	}

	public void setNewId(int newId) {
		this.newId = newId;
	}

	public String getAttachment1() {
		return attachment1;
	}

	public void setAttachment1(String attachment1) {
		this.attachment1 = attachment1;
	}

	public String getAttachment2() {
		return attachment2;
	}

	public void setAttachment2(String attachment2) {
		this.attachment2 = attachment2;
	}

	public String getAttachment3() {
		return attachment3;
	}

	public void setAttachment3(String attachment3) {
		this.attachment3 = attachment3;
	}

	public int getIterator() {
		return iterator;
	}

	public void setIterator(int iterator) {
		this.iterator = iterator;
	}

	public AdvertisementEntity getAdvertisement() {
		return advertisement;
	}

	public void setAdvertisement(AdvertisementEntity advertisement) {
		this.advertisement = advertisement;
	}

	public Map<String, AdvertisementTypeEntity> getTypes() {
		if (types == null)
			types = AdvertisementTypeEntityDAO.getAdvertisementTypes();
		return types;
	}

	public void setTypes(Map<String, AdvertisementTypeEntity> types) {
		this.types = types;
	}

	public Map<String, CategoryEntity> getCategories() {
		if (categories == null)
			categories = CategoryEntityDAO.getCategories();
		return categories;
	}

	public void setCategories(Map<String, CategoryEntity> categories) {
		this.categories = categories;
	}

	public String getSelectedType() {
		return selectedType;
	}

	public void setSelectedType(String selectedType) {
		this.selectedType = selectedType;
	}

	public String getSelectedCategory() {
		return selectedCategory;
	}

	public void setSelectedCategory(String selectedCategory) {
		this.selectedCategory = selectedCategory;
	}

	public UserEntity getUser() {
		return user;
	}

	public void setUser(UserEntity user) {
		this.user = user;
	}

	public String getRegAdvertisementStatus() {
		return regAdvertisementStatus;
	}

	public void setRegAdvertisementStatus(String regAdvertisementStatus) {
		this.regAdvertisementStatus = regAdvertisementStatus;
	}


	public String trySave() {

		FacesContext context = FacesContext.getCurrentInstance();
		Date now = new Date();
		if (advertisement.getStartDate().before(now) && !(advertisement.getStartDate().getDate()==now.getDate())) {
			context.addMessage("change", new FacesMessage(
					FacesMessage.SEVERITY_ERROR,
					"Nie można ustawić daty wcześniejszej niż aktualna!", ""));
			return null;

		} else {
			if (advertisement.getExpireDate() != null && (advertisement.getExpireDate().before(
					advertisement.getStartDate()) || advertisement.getExpireDate().equals(advertisement.getStartDate()))) {
				context.addMessage(
						"change",
						new FacesMessage(
								FacesMessage.SEVERITY_ERROR,
								"Data wygaśnięcia ogłoszenia nie może być wcześniejsza lub równa dacie jego rozpoczęcia!",
								""));
				return null;
			} else {

				Session session = HibernateManager.getSession();
				session.beginTransaction();
				UserEntity u = UserEntityDAO.getUserByLogin(session,
						user.getLogin());

				AttachmentEntity att1 = new AttachmentEntity();
				AttachmentEntity att2 = new AttachmentEntity();
				AttachmentEntity att3 = new AttachmentEntity();
				att1.setAdvertisement(advertisement);
				att2.setAdvertisement(advertisement);
				att3.setAdvertisement(advertisement);
				if (iterator > 1) {

					att1.setPath(attachment1);
				}
				if (iterator > 2) {

					att2.setPath(attachment2);
				}
				if (iterator > 3) {

					att3.setPath(attachment3);
				}

				advertisement.setUser(u);

				advertisement.getAttachments().add(att1);
				advertisement.getAttachments().add(att2);
				advertisement.getAttachments().add(att3);

				System.out.println("Kategoria" + getCategories().size());
				advertisement
						.setCategory(getCategories().get(selectedCategory));
				advertisement.setType(getTypes().get(selectedType));

				try {
					session.save(advertisement);
					for (AttachmentEntity at : advertisement.getAttachments())
						session.save(at);
					session.getTransaction().commit();
					context.addMessage("adding", new FacesMessage(
							FacesMessage.SEVERITY_INFO, "Dodano ogłoszenie"
									+ attachment1, ""));
					setNewId(AdvertisementEntityDAO.maxValueOfAdvertisement());

					return "myAdvertisements2";

				} catch (Exception ex) {
					session.getTransaction().rollback();
					context.addMessage(
							"change",
							new FacesMessage(
									FacesMessage.SEVERITY_ERROR,
									"Wystąpił błąd, ogłoszenie nie zostało dodane!",
									""));
					return null;
				} finally {
					session.close();
				}
			}
		}
	}

	public void handleFileUpload() throws IOException {
		if (upFile.getContentType().equals("image/jpeg") || upFile.getSize() > 1048576) {
			try {
				int pom = AdvertisementEntityDAO.maxValueOfAttachment()
						+ iterator;
				String prefix = FilenameUtils.getBaseName(String.valueOf(pom));

				FileOutputStream fos = new FileOutputStream(
						"/glassfishv3/glassfish/domains/domain1/eclipseApps/MIA/files/"
								+ prefix + ".jpg");
				InputStream is = upFile.getInputStream();
				byte[] tab = new byte[upFile.getBytes().length];
				is.read(tab, 0, upFile.getBytes().length);
				fos.write(tab);
				is.close();
				fos.close();

				if (iterator == 1)
					attachment1 = "files/" + prefix + ".jpg";
				if (iterator == 2)
					setAttachment2("files/" + prefix + ".jpg");
				if (iterator == 3) {
					setAttachment3("files/" + prefix + ".jpg");
					avalible = false;
				}

				FacesMessage msg = new FacesMessage("Załadowano plik "
						+ upFile.getName(), " is uploaded.");
				FacesContext.getCurrentInstance().addMessage("atta", msg);
				iterator = iterator + 1;

			} catch (Exception ioe) {

				FacesMessage msg = new FacesMessage(
						"Nie załadowano pliku: zdjęcie musi być w formacie *.jpg, nie większe od 1 MB",
						" is uploaded.");
				FacesContext.getCurrentInstance().addMessage("atta", msg);

			}
		} else {
			FacesMessage msg = new FacesMessage(
					"Nie załadowano pliku: zdjęcie musi być w formacie *.jpg, nie większe od 1 MB",
					" is uploaded.");
			FacesContext.getCurrentInstance().addMessage("atta", msg);
		}

	}
}
